<template>
  <div class="documents-container">
    <h1>我的文档</h1>

    <!-- 上传文档区域 -->
    <div class="upload-section">
      <h2>上传新文档</h2>
      <p class="upload-info">支持PDF、DOCX、TXT等格式，最大文件大小 50MB</p>

      <div class="upload-form">
        <input type="file" id="document-upload" ref="fileInput" @change="handleFileChange" accept=".pdf,.docx,.doc,.txt"
          class="file-input">
        <label for="document-upload" class="file-label">
          <span v-if="!selectedFile">选择文件</span>
          <span v-else>{{ selectedFile.name }} ({{ formatFileSize(selectedFile.size) }})</span>
        </label>

        <button @click="uploadDocument" class="btn-upload" :disabled="!selectedFile || uploading || fileSizeExceeded">
          {{ uploading ? '上传中...' : '上传文档' }}
        </button>
      </div>

      <!-- 文件大小错误提示 -->
      <div v-if="fileSizeExceeded" class="error-message">
        文件大小超过限制，最大允许 50MB
      </div>

      <!-- 上传进度条 -->
      <div v-if="uploadProgress > 0 && uploadProgress < 100" class="progress-container">
        <div class="progress-bar" :style="{ width: `${uploadProgress}%` }"></div>
        <span class="progress-text">{{ uploadProgress }}%</span>
      </div>
    </div>

    <!-- 文档列表 -->
    <div class="documents-list">
      <h2>我的文档列表</h2>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <p>加载中...</p>
      </div>

      <!-- 错误信息 -->
      <div v-if="error" class="error-message">
        {{ error }}
      </div>

      <!-- 成功消息 -->
      <div v-if="success" class="success-message">
        {{ success }}
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && !documents.length" class="empty-state">
        <p>您还没有上传任何文档</p>
      </div>

      <!-- 文档列表 -->
      <div v-if="!loading && documents.length" class="document-cards">
        <div v-for="document in documents" :key="document._id" class="document-card">
          <div class="document-info">
            <h3>{{ document.title || document.fileName }}</h3>
            <p class="document-meta">
              <span>{{ formatFileSize(document.fileSize) }}</span>
              <span>{{ formatDate(document.createdAt) }}</span>
              <span :class="['status', getStatusClass(document)]">
                {{ getStatusText(document) }}
              </span>
            </p>
            <p v-if="document.description" class="document-description">
              {{ document.description }}
            </p>
          </div>

          <div class="document-actions">
            <!-- 查看文档详情 -->
            <router-link :to="`/documents/${document._id}`" class="btn-view">
              查看
            </router-link>

            <!-- 处理文档按钮 -->
            <button v-if="canProcessDocument(document)" @click="processDocument(document._id)" class="btn-process"
              :disabled="processingDocId === document._id" :class="{ 'processing': processingDocId === document._id }">
              <span v-if="processingDocId === document._id">
                <span class="spinner"></span>
                处理中...
              </span>
              <span v-else>处理文档</span>
            </button>

            <!-- 删除文档按钮 -->
            <button @click="confirmDeleteDocument(document)" class="btn-delete">
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 确认删除对话框 -->
    <div v-if="showDeleteConfirm" class="delete-confirm-modal">
      <div class="modal-content">
        <h3>确认删除</h3>
        <p>确定要删除文档 "{{ documentToDelete?.title || documentToDelete?.fileName }}" 吗？</p>
        <p class="warning">此操作不可撤销，相关的知识卡片和练习题也将被删除。</p>

        <div class="modal-actions">
          <button @click="showDeleteConfirm = false" class="btn-cancel">取消</button>
          <button @click="deleteDocument" class="btn-confirm-delete">确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue';
import { useDocumentStore } from '@/store/document';
import { useRouter } from 'vue-router';

const documentStore = useDocumentStore();
const router = useRouter();

// 状态变量
const fileInput = ref(null);
const selectedFile = ref(null);
const uploading = ref(false);
const processingDocId = ref(null);
const showDeleteConfirm = ref(false);
const documentToDelete = ref(null);
const fileSizeExceeded = ref(false);
const success = ref(null);
const refreshInterval = ref(null); // 添加ref存储定时器ID
const error = ref(null); // 将error改为ref而不是computed

// 计算属性
const documents = computed(() => documentStore.getDocuments);
const loading = computed(() => documentStore.isLoading);
const uploadProgress = computed(() => documentStore.getUploadProgress);

// 生命周期钩子
onMounted(async () => {
  await fetchDocuments();

  // 设置定时刷新，每10分钟更新一次文档列表
  refreshInterval.value = setInterval(async () => {
    await documentStore.fetchDocuments();
  }, 1000 * 60 * 10);
});

// 在组件卸载时清除定时器
onUnmounted(() => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value);
    refreshInterval.value = null;
  }
});

// 方法
const fetchDocuments = async () => {
  await documentStore.fetchDocuments();
};

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    selectedFile.value = file;
    if (file.size > 50 * 1024 * 1024) {
      fileSizeExceeded.value = true;
    } else {
      fileSizeExceeded.value = false;
    }
  }
};

const uploadDocument = async () => {
  if (!selectedFile.value) return;

  if (fileSizeExceeded.value) {
    error.value = '文件大小超过限制，最大允许 50MB';
    return;
  }

  uploading.value = true;
  error.value = null;

  const formData = new FormData();
  formData.append('document', selectedFile.value);

  console.log('上传文件:', {
    name: selectedFile.value.name,
    size: selectedFile.value.size,
    type: selectedFile.value.type
  });

  try {
    const result = await documentStore.uploadDocument(formData);

    console.log('上传结果:', result);

    if (result.success) {
      // 重置文件输入
      selectedFile.value = null;
      if (fileInput.value) {
        fileInput.value.value = '';
      }

      // 显示成功消息
      success.value = '文档上传成功';
      setTimeout(() => {
        success.value = null;
      }, 3000);

      // 可以选择跳转到文档详情页
      // router.push(`/documents/${result.document._id}`);
    } else {
      error.value = result.error || '上传文档失败';
    }
  } catch (err) {
    console.error('上传文档失败:', err);
    error.value = err.response?.data?.message || '上传文档失败，可能是文件太大';
  } finally {
    uploading.value = false;
  }
};

const processDocument = async (documentId) => {
  processingDocId.value = documentId;
  error.value = null;

  try {
    // 显示处理中的提示
    success.value = '开始处理文档，系统将在后台继续处理，您可以离开此页面';

    const result = await documentStore.processDocument(documentId);

    if (result.success) {
      // 更新成功消息
      success.value = '文档处理请求已提交，系统正在后台处理中，请稍后刷新页面查看结果';
      setTimeout(() => {
        success.value = null;
      }, 8000);
    } else {
      error.value = result.error || '处理文档失败';
    }
  } catch (err) {
    console.error('处理文档失败:', err);
    if (err.code === 'ECONNABORTED') {
      error.value = '请求超时，但文档处理可能仍在后台进行，请稍后刷新页面查看结果';
    } else {
      error.value = err.response?.data?.message || '处理文档失败，请稍后再试';
    }
  } finally {
    processingDocId.value = null;
  }
};

const confirmDeleteDocument = (document) => {
  documentToDelete.value = document;
  showDeleteConfirm.value = true;
};

const deleteDocument = async () => {
  if (!documentToDelete.value) return;

  const documentId = documentToDelete.value._id;

  try {
    const result = await documentStore.deleteDocument(documentId);

    if (result.success) {
      showDeleteConfirm.value = false;
      documentToDelete.value = null;
      success.value = '文档已成功删除';
      setTimeout(() => {
        success.value = null;
      }, 3000);
    } else {
      error.value = result.error || '删除文档失败';
    }
  } catch (err) {
    console.error('删除文档失败:', err);
    error.value = err.response?.data?.message || '删除文档失败，请稍后再试';
  }
};

// 辅助函数
const formatFileSize = (bytes) => {
  if (bytes === undefined || bytes === null) return '未知大小';
  if (bytes === 0) return '0 B';

  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const formatDate = (dateString) => {
  if (!dateString) return '';

  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

const getStatusText = (document) => {
  if (!document) return '';

  // 优先检查processingStatus
  if (document.processingStatus === 'processing') {
    return '处理中';
  }
  if (document.processingStatus === 'failed') {
    return '处理失败';
  }
  if (document.processingStatus === 'completed' || document.processed) {
    return '已处理';
  }

  // 兼容旧状态字段
  const status = document.status;
  if (!status) return '待处理';

  const statusMap = {
    'UPLOADED': '待处理',
    'PROCESSED': '已处理',
    'PROCESSING': '处理中',
    'FAILED': '处理失败'
  };

  return statusMap[status] || status;
};

const getStatusClass = (document) => {
  if (!document) return '';

  // 优先使用processingStatus
  if (document.processingStatus === 'processing') {
    return 'processing';
  }
  if (document.processingStatus === 'failed') {
    return 'failed';
  }
  if (document.processingStatus === 'completed' || document.processed) {
    return 'processed';
  }

  // 兼容旧状态字段
  if (!document.status) return 'uploaded';
  return document.status.toLowerCase();
};

const canProcessDocument = (document) => {
  // 只有未处理且不在处理中的文档才能处理
  if (document.processingStatus === 'processing') {
    return false;
  }

  if (document.processingStatus === 'completed' || document.processed) {
    return false;
  }

  return true;
};
</script>

<style scoped>
.documents-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  margin-bottom: 2rem;
  color: #333;
}

h2 {
  margin-bottom: 1rem;
  color: #444;
}

.upload-section {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.upload-info {
  color: #666;
  margin-bottom: 1rem;
  font-size: 0.9rem;
}

.upload-form {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.file-input {
  display: none;
}

.file-label {
  padding: 0.75rem 1.5rem;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  flex-grow: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 60%;
}

.file-label:hover {
  background-color: #e8e8e8;
}

.btn-upload {
  padding: 0.75rem 1.5rem;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
}

.btn-upload:hover {
  background-color: #45a049;
}

.btn-upload:disabled {
  background-color: #9e9e9e;
  cursor: not-allowed;
}

.progress-container {
  margin-top: 1rem;
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  position: relative;
}

.progress-bar {
  height: 100%;
  background-color: #4CAF50;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  right: 0;
  top: -20px;
  font-size: 0.8rem;
  color: #666;
}

.documents-list {
  margin-top: 2rem;
}

.loading-container {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.error-message {
  color: #ff3860;
  background-color: #feecf0;
  padding: 1rem;
  border-radius: 4px;
  margin-bottom: 1rem;
}

.success-message {
  color: #4CAF50;
  background-color: #e8f5e9;
  padding: 1rem;
  border-radius: 4px;
  margin-bottom: 1rem;
}

.empty-state {
  text-align: center;
  padding: 3rem;
  background-color: #f9f9f9;
  border-radius: 8px;
  color: #666;
}

.document-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
}

.document-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 1.5rem;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.document-info h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #333;
}

.document-meta {
  display: flex;
  gap: 1rem;
  color: #666;
  font-size: 0.85rem;
  margin-bottom: 0.75rem;
}

.status {
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
}

.status.uploaded {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status.processing {
  background-color: #fff8e1;
  color: #ff8f00;
}

.status.processed {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status.error {
  background-color: #ffebee;
  color: #c62828;
}

.document-description {
  color: #555;
  margin-bottom: 1rem;
  font-size: 0.9rem;
  line-height: 1.5;
}

.document-actions {
  display: flex;
  gap: 0.75rem;
  margin-top: 1rem;
}

.btn-view,
.btn-process,
.btn-delete {
  padding: 0.5rem 1rem;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  flex: 1;
}

.btn-view {
  background-color: #2196F3;
  color: white;
  border: none;
}

.btn-view:hover {
  background-color: #1976D2;
}

.btn-process {
  background-color: #FF9800;
  color: white;
  border: none;
}

.btn-process:hover {
  background-color: #F57C00;
}

.btn-process:disabled {
  background-color: #9e9e9e;
  cursor: not-allowed;
}

.btn-delete {
  background-color: transparent;
  color: #F44336;
  border: 1px solid #F44336;
}

.btn-delete:hover {
  background-color: #ffebee;
}

/* 删除确认对话框 */
.delete-confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 2rem;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
}

.modal-content h3 {
  margin-top: 0;
  color: #333;
}

.warning {
  color: #F44336;
  font-weight: 500;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

.btn-cancel,
.btn-confirm-delete {
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
}

.btn-cancel {
  background-color: transparent;
  color: #333;
  border: 1px solid #ddd;
}

.btn-confirm-delete {
  background-color: #F44336;
  color: white;
  border: none;
}

.btn-confirm-delete:hover {
  background-color: #D32F2F;
}
</style>